package com.forlove.app.common.base.db.sqlite;


import com.forlove.app.common.base.db.table.Foreign;
import com.forlove.app.common.base.db.table.TableUtils;

import java.util.List;

public class ForeignLazyLoader<T> {
    private Foreign foreignColumn;
    private Object columnValue;

    public ForeignLazyLoader(Class<?> entityType, String columnName, Object columnValue) {
        this.foreignColumn = (Foreign) TableUtils.getColumnOrId(entityType, columnName);
        this.columnValue = columnValue;
    }

    public ForeignLazyLoader(Foreign foreignColumn, Object columnValue) {
        this.foreignColumn = foreignColumn;
        this.columnValue = columnValue;
    }

    public List<T> getAllFromDb() {
        List<T> entities = null;
        if (foreignColumn != null && foreignColumn.db != null) {
            entities = foreignColumn.db.findAll(Selector.from(foreignColumn.getForeignEntityType()).where(foreignColumn.getForeignColumnName(), "=", columnValue));
        }
        return entities;
    }

    public T getFirstFromDb() {
        T entity = null;
        if (foreignColumn != null && foreignColumn.db != null) {
            entity = foreignColumn.db.findFirst(Selector.from(foreignColumn.getForeignEntityType()).where(foreignColumn.getForeignColumnName(), "=", columnValue));
        }
        return entity;
    }

    public Object getColumnValue() {
        return columnValue;
    }
}
